package com.itheima.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.entity.Category;
import com.itheima.entity.Dish;
import com.itheima.entity.DishDto;
import com.itheima.entity.DishFlavor;
import com.itheima.service.CategoryService;
import com.itheima.service.DishFlavorService;
import com.itheima.service.DishService;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @Auther: 宋H
 * @Date: 2022/9/7
 * @Description: com.itheima.controller
 * @version: 1.0
 */
@RestController
@Slf4j
@RequestMapping("/dish")
@Api(tags="菜品相关接口")
public class DishController {
    @Autowired
    private DishService dishService;
    @Autowired
    private DishFlavorService dishFlavorService;
    @Autowired
    private CategoryService categoryService;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 添加菜品信息
     * @param dishDto
     * @return
     */
    @PostMapping
    public R<String> dishSave(@RequestBody DishDto dishDto){
        log.info(dishDto.toString());
        dishService.saveList(dishDto);

        //修改数据后为了同数据库的信息一致,需要删除缓存中对应的数据(清理菜品所有的数据)
        redisTemplate.delete(redisTemplate.keys("dish_*"));
        redisTemplate.delete(redisTemplate.keys("setmeal_*"));

        return R.success("添加成功");
    }

    /**
     * 菜品信息分页查询
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R<Page> dishPage(int page,int pageSize,String name){
        log.info("分页信息查询中,当前第{}页,每页查询{}个",page,pageSize);
        Page<Dish> dishPage=new Page<>(page,pageSize);
        Page<DishDto> dishDtoPage=new Page<>();

        LambdaQueryWrapper<Dish> lqw = new LambdaQueryWrapper<>();
        lqw.eq(name!=null,Dish::getName,name);
        lqw.orderByDesc(Dish::getUpdateTime);
        dishService.page(dishPage,lqw);

       /* 待执行完之后将分页查询的对象dishPage拷贝到dishDtoPage对象中,并忽略records数据属性
        因为dishDtoPage对象空数据需要用分页对象来进行填充*/

        //使用工具栏进行对象拷贝
        BeanUtils.copyProperties(dishPage,dishDtoPage,"records");
        List<Dish> records = dishPage.getRecords();//里面存在ctegoryId,这时可以用来获取Category对象来获取分类名称
        List<DishDto> list= records.stream().map((item)->{
            DishDto dishDto=new DishDto();
            BeanUtils.copyProperties(item,dishDto);//把每一个records拷贝给DishDto对象

            Long categoryId = item.getCategoryId();//获取分类id,因为最终需要通过分类id,查询分类名称

            //根据id查询分类对象
            Category category = categoryService.getById(categoryId);
            if(category!=null){//当菜品分类对象为空时不进行菜品分类赋值
                String categoryName = category.getName();
                dishDto.setCategoryName(categoryName);
            }
            return dishDto;
        }).collect(Collectors.toList());

        dishDtoPage.setRecords(list);
        return R.success(dishDtoPage);
    }

    /**
     * 根据菜品id获取菜品信息和对应的口味信息
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<DishDto> dishById(@PathVariable Long id){
        log.info("查询菜品id={},对应的信息中",id);
        DishDto dishDto = dishService.getDishFlavorById(id);
        return R.success(dishDto);
    }

    /**
     * 修改菜品信息
     * @param dishDto
     * @return
     */
    @PutMapping
    public R<String> dishUpdate(@RequestBody DishDto dishDto){
        log.info(dishDto.toString());
        dishService.dishUpadate(dishDto);

        //修改数据后为了同数据库的信息一致,需要删除缓存中对应的数据(清理菜品所有的数据)
        Set keys = redisTemplate.keys("dish_*");
        Set keys1 = redisTemplate.keys("setmeal_*");
        redisTemplate.delete(keys);
        redisTemplate.delete(keys1);

        //清理某个分类下面的菜品缓存数据
//        String key = "dish_"+dishDto.getCategoryId()+"_"+dishDto.getStatus();
//        redisTemplate.delete(key);
        return R.success("修改成功");
    }

    /**
     * 菜品启售/停售（单个或批量
     * @param ids
     * @return
     */
    @PostMapping("/status/{status}")
    public R<String> dishStatus(@PathVariable("status") Integer status,@RequestParam List<Long> ids){
        log.info("状态,{}",status);
        log.info("修改菜品,{}",ids);
        dishService.dishStatus(status,ids);
        LambdaQueryWrapper<Dish> lqw = new LambdaQueryWrapper<>();
        lqw.in(ids!=null,Dish::getId,ids);
        List<Dish> list = dishService.list(lqw);
        for (Dish dish : list) {
            Long categoryId = dish.getCategoryId();
            String key = "dish_" + categoryId + "_1";
            if(dish!=null){
                //修改数据后为了同数据库的信息一致,需要删除缓存中对应的数据(清理处于停售商品的菜品信息)
                redisTemplate.delete(key);
            }
        }


        return R.success("菜品售卖状态修改成功");
    }

    /**
     *  查询菜品Id,删除指定菜品
     * @param ids
     * @return {@link R< String>}
     */
    @DeleteMapping
    public R<String> dishDelete(@RequestParam("ids") List<Long> ids){
        log.info("删除菜品,{}",ids);
//        //新增商品后需要删除缓存
//        LambdaQueryWrapper<Dish> lqw1 = new LambdaQueryWrapper<>();
//        lqw1.in(ids!=null,Dish::getId,ids);
//        List<Dish> list = dishService.list(lqw1);
//        for (Dish dish : list) {
//            Long categoryId = dish.getCategoryId();
//            String key = "dish_" + categoryId + "_1";
//            if(dish!=null){
//                //修改数据后为了同数据库的信息一致,需要删除缓存中对应的数据(清理处于停售商品的菜品信息)
//                redisTemplate.delete(key);
//            }
//        }
        //删除菜品信息
        dishService.dishRemove(ids);

        //再删除菜品对应的口味信息
        LambdaQueryWrapper<DishFlavor> lqw = new LambdaQueryWrapper<>();
        lqw.in(DishFlavor::getDishId,ids);
        dishFlavorService.remove(lqw);
        return R.success("菜品及其对应口味信息删除成功");
    }

//    /**
//     * 根据id查询菜品信息
//     * @return
//     */
//    @GetMapping("/list")
//    public R<List<Dish>> cateoryGetById(Dish dish){
//        log.info(dish.toString());
//
//        LambdaQueryWrapper<Dish> lqw = new LambdaQueryWrapper<>();
//        lqw.eq(dish.getCategoryId()!=null,Dish::getCategoryId,dish.getCategoryId()).eq(Dish::getStatus,1);
//        lqw.orderByDesc(Dish::getSort);
//
//        List<Dish> dishList = dishService.list(lqw);
//        return R.success(dishList);
//    }

    /**
     * 根据id查询菜品信息
     * @return
     */
    @GetMapping("/list")
    public R<List<DishDto>> cateoryGetById(Dish dish){
        log.info(dish.toString());
        List<DishDto> dishDtoList;
        String dishkey="dish_"+dish.getCategoryId()+"_"+dish.getStatus();

        //从Redis缓存中获取数据,如果有直接返回,没有需要查询后添加到Redis中
        dishDtoList = (List<DishDto>) redisTemplate.opsForValue().get(dishkey);

        if(dishDtoList!=null){
            return R.success(dishDtoList);
        }else{
            LambdaQueryWrapper<Dish> lqw = new LambdaQueryWrapper<>();
            lqw.eq(dish.getCategoryId()!=null,Dish::getCategoryId,dish.getCategoryId()).eq(Dish::getStatus,1);
            lqw.orderByDesc(Dish::getSort);
            List<Dish> dishList = dishService.list(lqw);

            dishDtoList= dishList.stream().map((item)->{
                DishDto dishDto=new DishDto();
                BeanUtils.copyProperties(item,dishDto);//把每一个records拷贝给DishDto对象

                Long categoryId = item.getCategoryId();//获取分类id,因为最终需要通过分类id,查询分类名称

                //根据id查询分类对象
                Category category = categoryService.getById(categoryId);
                if(category!=null){//当菜品分类对象为空时不进行菜品分类赋值
                    String categoryName = category.getName();
                    dishDto.setCategoryName(categoryName);
                }
                Long dishid = item.getId();
                LambdaQueryWrapper<DishFlavor> QueryWrapper = new LambdaQueryWrapper<>();
                QueryWrapper.eq(DishFlavor::getDishId,dishid);
                List<DishFlavor> dishFlavorList = dishFlavorService.list(QueryWrapper);
                dishDto.setFlavors(dishFlavorList);
                return dishDto;
            }).collect(Collectors.toList());
            redisTemplate.opsForValue().set(dishkey,dishDtoList);
        }

        return R.success(dishDtoList);
    }
}
